import 'package:flutter/material.dart';
import '/plugin/dio_new/dio_new.dart';
import 'package:get/get.dart';
import '/plugin/tree/custom_tree_view.dart';
import '/plugin/tree/app_controller.dart';
import 'package:animations/animations.dart';

class TreeSelect extends StatefulWidget {
  final String title;
  final bool required;
  final String loadUrl;
  final ValueChanged<String>? onChange;
  final bool multiple;
  TreeSelect({
    Key? key,
    required this.title,
    required this.required,
    required this.loadUrl,
    this.onChange,
    required this.multiple,
  }) : super(key: key);

  @override
  _TreeSelectState createState() => _TreeSelectState();
}

class _TreeSelectState extends State<TreeSelect> {
  late Widget labelText;
  late String selectString = '请选择';
  late HttpClient dio;
  Map selectedValue = new Map();
  List selectedList = [];
  late DetailPageController c;
  ContainerTransitionType _transitionType = ContainerTransitionType.fade;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    dio = Get.find<HttpClient>();
    // 使用Get.put()实例化你的类，使其对当下的所有子路由可用。
    c = Get.put(DetailPageController());
    c.setLoadUrl(widget.loadUrl);
    c.setMultiple(widget.multiple);
    initRequiredLabel();
  }

  void initRequiredLabel() {
    if (widget.required) {
      labelText = Row(
        children: [
          Text(
            '* ',
            style: TextStyle(color: Colors.red),
          ),
          Text(widget.title),
        ],
      );
    } else {
      labelText = Text(widget.title);
    }
  }

  void _showMarkedAsDoneSnackbar(context, bool? isMarkedAsDone) {
    DetailPageController c = Get.find();
    var strArr = [];
    selectedValue = c.selectedValue;
    selectedValue.forEach((key, value) {
      selectedList.add(key);
      strArr.add(value);
    });
    if (strArr.length > 0) {
      selectString = strArr.join(',');
    }
    widget.onChange?.call(selectedList.join(','));
    if (isMarkedAsDone ?? false)
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text('选择完成'),
      ));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          OpenContainer<bool>(
            transitionType: _transitionType,
            openBuilder: (BuildContext _, VoidCallback openContainer) {
              return const _DetailsPage();
            },
            onClosed: (context) => _showMarkedAsDoneSnackbar(context, null),
            tappable: false,
            closedShape: const RoundedRectangleBorder(),
            closedElevation: 0.0,
            closedBuilder: (BuildContext _, VoidCallback openContainer) {
              return InkWell(
                onTap: () => {openContainer()},
                child: Container(
                  color: Colors.white,
                  child: ListTile(
                    title: labelText,
                    trailing: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Container(
                          width: 150,
                          padding: EdgeInsets.all(5),
                          child: Text(
                            selectString,
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                            textAlign: TextAlign.right,
                          ),
                        ),
                        selectString == '请选择'
                            ? Icon(Icons.keyboard_arrow_right)
                            : Text(''),
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
          Divider(height: 1, indent: 20),
        ],
      ),
    );
  }
}

class _DetailsPage extends StatefulWidget {
  const _DetailsPage({Key? key}) : super(key: key);

  @override
  __DetailsPageState createState() => __DetailsPageState();
}

class __DetailsPageState extends State<_DetailsPage> {
  AppController appController = AppController();
  DetailPageController c = Get.find();
  List _treeData = [];
  late HttpClient dio;

  bool _isRequest = false;
  @override
  void dispose() {
    appController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    dio = Get.find<HttpClient>();
    initData();
  }

  initData() async {
    appController.multiple = c.multiple;
    if (_treeData.isNotEmpty) {
      await appController.init();
      return;
    } else if (_isRequest) {
      //如果已经请求过了。直接return 避免重复调用接口
      return;
    } else {
      _isRequest = true;
      HttpResponse appResponse =
          await dio.get(c.loadUrl, queryParameters: {"searchAll": false});
      if (appResponse.ok) {
        _treeData = appResponse.data;
        appController.treeData = _treeData;
        appController.initValue = c.selectedValue;

        await appController.init();
      } else {
        _treeData = [];
        appController.treeData = [];
        appController.initValue = {};
        await appController.init();
      }
    }
  }

  void _saveSelected() {
    c.setSelectedValue(appController.selectedValue);
    Navigator.pop(context, true);
  }

  @override
  Widget build(BuildContext context) {
    return AppControllerScope(
      controller: appController,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('请选择'),
          actions: <Widget>[
            IconButton(
              icon: const Icon(Icons.done),
              onPressed: () => _saveSelected(),
              tooltip: '选择完成',
            )
          ],
        ),
        body: FutureBuilder<void>(
          future: initData(),
          builder: (_, __) {
            if (appController.isInitialized) {
              if (appController.treeData.isNotEmpty) {
                return const _Unfocus(child: CustomTreeView());
              } else {
                return Center(
                  child: Text('暂无数据'),
                );
              }
            }
            return const Center(child: CircularProgressIndicator());
          },
        ),
      ),
    );
  }
}

class _Unfocus extends StatelessWidget {
  const _Unfocus({Key? key, required this.child}) : super(key: key);

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: FocusScope.of(context).unfocus,
      child: child,
    );
  }
}

class DetailPageController extends GetxController {
  String loadUrl = '';
  Map selectedValue = new Map();
  bool multiple = true;
  List selectedStringList = [];
  setMultiple(bool val) => this.multiple = val;
  setLoadUrl(String val) => this.loadUrl = val;
  setSelectedValue(Map val) => this.selectedValue = val;
  setselectedStringList(List val) => this.selectedStringList = val;
}
